package com.io.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 工具类
 */
public class MyBatisUtil {
    private static SqlSessionFactory factory;//Sql会话工厂对象,单例
    static{//通过静态代码块,唯一一次创建SqlSessionFactory实例

    }
    /**
     * 创建并返回SqlSession实例
     * @return 返回: SqlSession对象
     */
    public static SqlSession createSqlSession(){
        if(factory == null){
            try {
                //读取MyBatis核心配置文件
                InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
                //由SqlSessionFactoryBuilder会话工厂建造对象 根据核心配置文件创建SqlSessionFactory会话工厂对象
                factory = new SqlSessionFactoryBuilder().build(is);
                System.out.println("初始化成功!");
            } catch (IOException e) {
                //throw new RuntimeException("初始化失败",e)
                e.printStackTrace();
            }
        }
        //关闭自动提交事务
        return factory.openSession();
    }
    /**
     * 关闭SqlSession
     * @param sqlSession
     */
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession != null){//判断如果sql会话不为空则关闭连接
            sqlSession.close();//关闭sql会话
        }
    }
}
